"""
在线阅读 : 服务端数据处理
"""

import pymysql
import hashlib

class HashEncryption:
    def sha512(self,password):
        #固定的盐
        hash = hashlib.sha512(b"*#06#")
        hash.update(password.encode())
        return hash.hexdigest()

class Data:
    def __init__(self):
        self.kwargs = {"host": "localhost",
              "port": 3306,
              "user": "root",
              "password": "123456",
              "database": "dict",
              "charset": "utf8", }
        self.db = pymysql.connect(**self.kwargs)
        self.cur = self.db.cursor()
        self.id = None
        self.encryption = HashEncryption()

    def close(self):
        self.cur.close()
        self.db.close()

    def register(self,name,password):
        password = self.encryption.sha512(password)
        sql = "insert into user (name,password) values (%s,%s);"
        try:
            self.cur.execute(sql,[name,password])
            self.db.commit()
            return True
        except Exception as e:
            print(e)
            self.db.rollback()
            return False

    def login(self, name, password):
        password = self.encryption.sha512(password)
        sql = "select id from user where name = %s and password = %s;"
        self.cur.execute(sql,[name,password])
        return self.cur.fetchone()

    def qury(self,word):
        sql = "select mean from word where word = %s;"
        try:
            self.cur.execute(sql,[word])
            explain = self.cur.fetchone()
            return explain
        except Exception as e:
            print(e)
            return False

    def insert_hist(self,user_id,word):
        sql = "insert into history (user_id,word) values (%s,%s)"
        try:
            self.cur.execute(sql, [user_id,word])
            self.db.commit()
        except Exception as e:
            print(e)
            return False

    def hist(self,user_id):
        sql = "select name,word,time " \
              "from history inner join user " \
              "on history.user_id = user.id " \
              "where user_id = %s " \
              "order by time desc " \
              "limit 10;"
        self.cur.execute(sql,[user_id])
        return self.cur.fetchall()








